/**
 * Created by ZHOUSH on 1/18/2016.
 */
var xml2js = require('xml2js');
var Promise = require('promise');
var fs = require('fs');
var pread = Promise.denodeify(fs.readFile);
var pwrite = Promise.denodeify(fs.writeFile);
var pxml2js = Promise.denodeify(xml2js.parseString);
pread('connections.xml', 'utf-8').then(function (data) {
    return pxml2js(data);
}).then(function (data) {
    var obj = data['References'];
    var tns = [];
    var tns_fmt = '{0} = \r\n' +
        '  (DESCRIPTION = \r\n' +
        '    (ADDRESS_LIST = \r\n' +
        '       (ADDRESS = (PROTOCOL = TCP)(HOST = {1})(PORT = {2}))\r\n' +
        '    )\r\n' +
        '    (CONNECT_DATA = \r\n' +
        '      ({3})\r\n' +
        '      (SERVER = DEDICATED)\r\n' +
        '    )\r\n' +
        '  )\r\n';
    var attr = function (conn, name) {
        var ref = conn['RefAddresses'][0]['StringRefAddr'].filter(function (sra) {
            return sra.$.addrType == name
        });
        if (ref.length > 0) {
            return ref[0]['Contents'][0];
        } else {
            return null;
        }
    };
    tns = obj['Reference'].map(function (item) {
        var name = item.$.name.replace(/\s+/ig, '_');
        var host = attr(item, 'hostname');
        var port = attr(item, 'port');
        var serviceName = attr(item, 'serviceName');
        var sid = attr(item, 'sid');
        var str = tns_fmt.replace('{0}',name).replace('{1}',host).replace('{2}',port);
        if (sid) {
            return str.replace('{3}', 'SID = ' + sid);
        } else if (serviceName) {
            return str.replace('{3}', 'SERVICE_NAME = ' + serviceName);
        }
    });
    return pwrite('tnsnames.ora', tns.join('\r\n\r\n'));
}, function (err) {
    console.log(err.stack);
});